package cn.thornbird.orgsync.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ReflectUtil {

    public static Object getValue(Object object, String name) {
        Object value = null;
        try {
            Field field = getField(object, name);
            if (field != null) {
                field.setAccessible(true);
                value = field.get(object);
            }
        } catch (IllegalAccessException e) {
            log.error("error", e);
        }
        return value;
    }

    public static Map<String, Object> getValues(Object object) {
        Map<String, Object> values = new HashMap<>();
        try {
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                values.put(field.getName(), field.get(object));
            }
        } catch (IllegalAccessException e) {
            log.error("error", e);
        }
        return values;
    }

    public static Field getField(Object object, String name) {
        List<Field> fields = new ArrayList<>();
        Class<?> clazz = object.getClass();
        while (clazz != null) {
            fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fields.stream().filter(f -> f.getName().equals(name)).findFirst().orElse(null);
    }

    public static Method getMethod(Object object, String name) {
        List<Method> methods = new ArrayList<>();
        Class<?> clazz = object.getClass();
        while (clazz != null) {
            methods.addAll(Arrays.asList(clazz.getDeclaredMethods()));
            clazz = clazz.getSuperclass();
        }
        return methods.stream().filter(m -> m.getName().equals(name)).findFirst().orElse(null);
    }

}
